package com.hyt.it.ogt.kq.service.bm.den;

import java.io.InputStream;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.Xpp3Driver;

/**
 * 输出xml和解析xml的工具类
 * 
 * @ClassName:XmlUtil
 * @author: chenyoulong Email: chen.youlong@payeco.com
 * @date :2012-9-29 上午9:51:28
 */
public class XmlUtils {
	/**
	 * java 转换成xml
	 * 
	 * @Title: toXml
	 * @param obj 对象实例
	 * @return String xml字符串
	 */
	public static String toXml(Object obj) {
		XStream xstream = new XStream();
		xstream.processAnnotations(obj.getClass()); // 通过注解方式的，一定要有这句话
		return xstream.toXML(obj);
	}

	/**
	 * 避免xml内容中存在下划线时，会变成两条下划线
	 * 
	 * @param obj
	 * @return
	 */
	public static String toXmlByNoNameCoder(Object obj) {
		XStream xstream = new XStream(new Xpp3Driver(new NoNameCoder()));
		//// 如果没有这句，xml中的根元素会是<包.类名>；或者说：注解根本就没生效，所以的元素名就是类的属性
		xstream.processAnnotations(obj.getClass()); // 通过注解方式的，一定要有这句话
		return xstream.toXML(obj);
	}


	/**
	 * 将传入xml文本转换成Java对象
	 * 
	 * @Title: toBean
	 * @param xmlStr
	 * @param cls    xml对应的class类
	 * @return T xml对应的class类的实例对象
	 * 
	 *         调用的方法实例：PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class);
	 */
	public static <T> T toBean(String xmlStr, Class<T> cls) {
		// 注意：不是new Xstream(); 否则报错：java.lang.NoClassDefFoundError:
		// org/xmlpull/v1/XmlPullParserFactory
		XStream xstream = new XStream(new DomDriver());
		xstream.processAnnotations(cls);
		T obj = (T) xstream.fromXML(xmlStr);
		return obj;
	}



	

	/**
	 * 从xml文件读取报文
	 * 
	 * @Title: toBeanFromFile
	 * @param cls
	 * @throws Exception
	 * @return T
	 */
	public static <T> T toBeanFromInputStream(InputStream ins, Class<T> cls) throws Exception {

		XStream xstream = new XStream(new DomDriver("UTF-8"));
		xstream.processAnnotations(cls);
		T obj = null;
		try {
			obj = (T) xstream.fromXML(ins);
		} catch (Exception e) {
			throw new Exception("解析文件失败！", e);
		}
		if (ins != null)
			ins.close();
		return obj;
	}

	
}
